// 柱状图组件
import { memo } from 'react';
import * as echarts from 'echarts/core';
import { GridComponent, GridComponentOption, TitleComponent } from 'echarts/components';
import { BarChart, BarSeriesOption } from 'echarts/charts';
import { CanvasRenderer } from 'echarts/renderers';

echarts.use([GridComponent, BarChart, TitleComponent, CanvasRenderer]);

type EChartsOption = echarts.ComposeOption<GridComponentOption | BarSeriesOption>;

const MyBarChart = memo(({ chartTitle, xData, yData }: { 
  chartTitle: string, xData: string[] | number [], yData: number[] 
}) => {
  const chartRef = useRef(null)
  useEffect(() => {
    const option: EChartsOption = {  // 图标配置参数
      title: {
        text: chartTitle,
      },
      xAxis: {
        type: 'category',
        data: xData
      },
      yAxis: {
        type: 'value',
      },
      series: [
        {
          data: yData,
          type: 'bar'
        }
      ]
    };
    const element = chartRef.current // 获取要渲染的dom节点
    if(element){
      const myChart = echarts.init(element); // 节点的初始化生成图表实例
      option && myChart.setOption(option);  // 使用图表参数渲染
    }
  }, [])

  return (
    <div ref={chartRef} style={{ width: "400px", height: "300px" }}></div>
  )
})
export default MyBarChart